/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.pig.pigpen.actions;

import java.util.Iterator;

import org.apache.pig.pigpen.view.ExampleTreeViewer;
import org.apache.pig.pigpen.view.LaunchWindowView;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;

// some helper methods for the action delegates
public class ActionDelegateHelper {

    public static enum VIEW {
        LAUNCHVIEW, EXAMPLEVIEW,
    }

    public static void ShowLauncher(IWorkbenchPage page, IFile file,
            VIEW viewType) throws PartInitException {
        switch (viewType) {
        case LAUNCHVIEW:
            page.showView(LaunchWindowView.VIEW_ID, file.toString(),
                    IWorkbenchPage.VIEW_ACTIVATE);
            break;
        case EXAMPLEVIEW:
            page.showView(ExampleTreeViewer.VIEW_ID, file.toString(),
                    IWorkbenchPage.VIEW_ACTIVATE);
            break;
        }
    }

    public static IViewReference GetLauncherReference(IWorkbenchPage page,
            IFile file, VIEW viewType) {
        switch (viewType) {
        case LAUNCHVIEW:
            return page.findViewReference(LaunchWindowView.VIEW_ID, file
                    .toString());
        case EXAMPLEVIEW:
            return page.findViewReference(ExampleTreeViewer.VIEW_ID, file
                    .toString());
        }

        return null;
    }

    public static IFile GetSelectedFile(ISelection selection) {
        if (!(selection instanceof IStructuredSelection))
            return null;
        Iterator iter = ((IStructuredSelection) selection).iterator();
        if (!iter.hasNext())
            return null;
        Object elem = iter.next();
        if (!(elem instanceof IAdaptable))
            return null;
        return (IFile) ((IAdaptable) elem).getAdapter(IFile.class);
    }
}
